﻿using System;
using System.IO;
using System.Web;
using Rabbit.Logic;
using RabbitManage.Code;
using Raven.Imports.Newtonsoft.Json;

namespace RabbitManage.Action
{
    public partial class ProductAdd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies[Constant.CookieName];
            string shopId = cookie.Values[Constant.CookieUid];

            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            if (!string.IsNullOrEmpty(postContent))
            {
                try
                {
                    Product item = JsonConvert.DeserializeObject<Product>(postContent);
                    string id = Request["id"];
                    if (!string.IsNullOrEmpty(id))
                    {
                        Product product = RabbitUse.GetProductById(Db.Store, id);
                        product.ShopId = shopId;

                        product.Description = item.Description;
                        product.GrossWeight = item.GrossWeight;
                        product.MainImage = item.MainImage;
                        product.Name = item.Name;
                        product.NetWeight = item.NetWeight;
                        product.PricePerUnit = item.PricePerUnit;
                        product.ProductionDate = item.ProductionDate;
                        product.Quantity = item.Quantity;
                        product.SubTitle = item.SubTitle;
                        product.Title = item.Title;

                        RabbitUse.AddProduct(Db.Store, product);
                    }
                    else
                    {
                        item.ShopId = shopId;
                        RabbitUse.AddProduct(Db.Store, item);
                    }
                    
                    Response.Write("true");
                }
                catch (Exception ex) 
                {
                    Response.Write(ex.Message);
                }
            }
            else
            {
                Response.Write("false");
            }
        }
    }
}